﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using ApriBox.Mvc.UploadHelpers;
using EF;
using BL;
using BL.Entities;

namespace ApriBox.Mvc.Controllers
{
    /// <summary>
    /// Контроллер для вывода списка файлов\папок
    /// </summary>
    [Authorize]
   
    public class HomeController : Controller
    {
        FSEntitiesRepository repository = new FSEntitiesRepository();

        
        public ActionResult Index()
        {       
     

            if (HttpContext.User.Identity.Name != null)
            {
                if (!repository.IsExistRootFolder(HttpContext.User.Identity.Name))
                    repository.CreateRootFolder(HttpContext.User.Identity.Name);
            
            }

            int homefolder = repository.GetRootId(HttpContext.User.Identity.Name);
            ViewBag.homefolder = homefolder;
            int folder = RouteData.Values["id"] == null ? homefolder : Convert.ToInt32(RouteData.Values["id"]);
            
            //Current folder
            try
            {
                //??
                if (repository.GetFoldersById(folder).Id != homefolder)
                {
                    if (repository.GetFoldersById(folder).Owner != HttpContext.User.Identity.Name)
                        return Content("You are trying to access foreign page!");

                    ViewBag.CurrentFolder = repository.GetFoldersById(folder).Name;
                }
                else
                    ViewBag.CurrentFolder = "ApriBox";
            }
            catch
            {
                ViewBag.CurrentFolder = "There are no folders";
            }

            //////////////////////Вытаскивает из БД лист фолдеров до родительской. Нужен для обратно хождения по папкам
            #region BackStepFolders

            List<Folder> response = new List<Folder>();

            Folder currentFolder;
            if (repository.GetParentFoldersById(folder)==null) currentFolder = repository.GetFoldersById(homefolder);
            //else  currentFolder = repository.GetParentFoldersById(folder);
            else currentFolder = repository.GetFoldersById(folder);

			ViewBag.currentFolderId = folder;
            response.Add(currentFolder);

            while (currentFolder.Id != homefolder)
            {
                currentFolder = repository.GetParentFoldersById(currentFolder.Id);
                response.Add(currentFolder);
            }


            response.Reverse();
            ViewBag.FolderStruct = response;
            #endregion


            //Обьем в мегабайтах который разрешаеться хранить юзеру
            int allowedCapacity = repository.GetAllowedCapacity(HttpContext.User.Identity.Name);
            if (allowedCapacity > 1023) ViewBag.AllowedCapacity = allowedCapacity / 1024 + "Gb";
            else ViewBag.AllowedCapacity = allowedCapacity + "Mb";
            
            //Текущий обьем в мегабайтах который занимает юзер
            int storageCapacity = repository.GetStorageCapacity(HttpContext.User.Identity.Name);
            if (storageCapacity > 1023) ViewBag.StorageCapacity = storageCapacity / 1024 + "Gb";
            else ViewBag.StorageCapacity = storageCapacity + "Mb";

            ViewBag.AllowedSize = allowedCapacity - storageCapacity;

            try { 
            ViewBag.PercentSpaceInStorage = storageCapacity * 100 / allowedCapacity;
                }
            catch
            {
                ViewBag.PercentSpaceInStorage = 0;
            }

            //////////
            if (Request.IsAjaxRequest())
            {
                return PartialView("_MainPartial", repository.GetFilesFoldersListById(folder));
            }


                return View(repository.GetFilesFoldersListById(homefolder));
        }





        [AllowAnonymous]
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        [AllowAnonymous]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }









    }
}
